<template>
  <!-- 我的学米 -->
  <div id="learnmi" class="learnmi">
    <div class="learnmiCont">
      <div class="learnmiCont_top content">
        <p>剩余可用学米</p>
        <p>{{ xuemi }}学米</p>
        <div class="learnmiCont_top_bot">
          学米用途：一定的学米可在网站兑换各种视频观看资格，文献下载权限，及查重费用等等。（1元100学米）
        </div>
      </div>
      <div class="learnmiCont_pay">
        <div class="learnmiCont_pay_left">
          <input
            class="textarea"
            v-model="xuepay"
            size="small"
            type="number"
            id="xuepay"
            @input="xuepayChange"
          />
          <span style="display: inline-block; margin-left: 10px">元</span>
        </div>
        <div class="learnmiCont_pay_right" @click="getdhpaymethods()">
          立即兑换
        </div>
        <!-- <el-button class="learnmiCont_pay_right" @click="getWxPay()"  :disabled="perdisabled" id="url">立即兑换</el-button> -->
        <div style="clear: both"></div>
      </div>
      <div class="learnmiCont_paymethods" v-show="patMethodsShow">
        <div class="acacirleCont_pay_cont">
          <div class="acacirleCont_pay_line"></div>
          <span>选择支付方式</span>
        </div>
        <ul>
          <li id="url">
            <div class="wxPay">
              <van-button type="primary" @click="H5getWxPay">微信支付</van-button>
			  
			  <van-button type="info" @click="getzfbPay" style='margin-left: 30rpx;' >支付宝支付</van-button>
            </div>
            <!-- <van-radio-group :value="radio">
              <van-cell-group>
                <van-cell
                  title="微信支付"
                  clickable
                  data-name="1"
                  @click="getWxPay"
                >
                  <van-radio slot="right-icon" name="1" />
                </van-cell>
              </van-cell-group>
            </van-radio-group> -->
          </li>
          <!-- <img src="../../../static/Vip/微信支付.png" alt />
            <el-radio v-model="radio" label="1" @change="getWxPay()"
              >微信支付</el-radio
            >
         
          <li>
            <img src="../../../static/Vip/支付宝支付.png" alt />
            <el-radio v-model="radio" label="2" @change="getzfbPay()"
              >支付宝支付</el-radio
            >
          </li> -->
        </ul>
      </div>
      <div class="learnmiCont_cont">
        <scroll-view
          lower-threshold="100"
          :style="'height:' + scrollHeight + 'px'"
          scroll-y
          @scrolltolower="pageChange"
        >
          <ul>
            <li class="">消费记录</li>
            <li v-for="(item, index) in cont_learnmB" :key="index">
              <p>
                <span>{{ item.Particulars }}</span>
                <span>{{ item.XueM }}学米</span>
              </p>
              <p>{{ item.AddDate }}</p>
            </li>
            <div class="consumption" v-if="!cont_learnmB.length">
              暂无消费记录
            </div>
            <!-- <el-pagination
            class="r"
            @size-change="handleSizeChange"
            @current-change="handleCurrentPageChange"
            :current-page="page.currentPage"
            :page-sizes="page.sizes"
            :page-size="page.pageSize"
            :total="page.total"
          ></el-pagination> -->
          </ul>
        </scroll-view>
      </div>
    </div>
  </div>
</template>

<script>
// import router from "@/router/index";
import util from "@/util/pay.js";
export default {
  name: "learnmi",
  data() {
    return {
      xuepay: "",
      // 消费记录
      cont_learnmB: [],
      xuemi: "",
      perdisabled: false,
      moxewxdata: [],
      moxezfbdata: [],
      radio: "",
      patMethodsShow: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      scrollHeight: 0,
      payThree: false,
    };
  },
  methods: {
	  H5getWxPay() {
	  	this.movipwxdata = util.getWxpaydetail(2, 2, 298, "string");
	  	this.movipwxdata.then(data => {
	  		// pc端
	  		// if (data.data.data.Code == 200) {
	  		// 	$(".paymethod_code").css("display", "block");
	  		// 	$("#wxpay").html("");
	  		// 	var qrcode = new QRCode(document.getElementById("wxpay"), {
	  		// 		width: 100,
	  		// 		height: 100
	  		// 	});
	  		// 	qrcode.makeCode(data.data.data.data.qrCodeUrl);
	  		// 	this.wxOrderNumber = data.data.data.data.OutTradeNo;
	  		// 	var _this = this;
	  		// 	this.timer = setInterval(() => {
	  		// 		_this.WxPayOK();
	  		// 	}, 3000);
	  		// }
	  		// 移动端
	  		 if (data.data.code == 200) {
	  		
	  				location.href = data.data.data.qrCodeUrl;
	  		} else {
	  			alert("生成订单失败");
	  		}
	  	});
	  },
    xuepayChange(e) {
      if (parseInt(Number(e.mp.detail.value))) {
        this.xuepay = parseInt(e.mp.detail.value);
      } else {
        this.xuepay = null;
      }
    },
    pageChange() {
      if (this.page.total <= this.cont_learnmB.length) return;
      this.page.currentPage += 1;
      this.getTableData();
    },
    getInfo() {
      this.getTableData();
    },
    // 消费记录
    getTableData() {
      this.$httphelper
        .post("/api/LmUserApi/GetExpenSecalendar", {
          OpenId: this.$localStorage.getItem("AuthorId"),
          Page: this.page.currentPage,
          Limit: this.page.pageSize,
        })
        .then((res) => {
          this.cont_learnmB = [...this.cont_learnmB, ...res.data.data];
          this.cont_learnmB.forEach((item) => {
            41;
            item.AddDate = item.AddDate.substr(0, 10);
            if (item.Particulars == "video" || item.Particulars == "video") {
              item.Particulars = "视频观看";
            } else if (item.Particulars == "paper") {
              item.Particulars = "论文下载";
            }
          });
          this.page.total = res.data.totalcount;
        })
        .catch((err) => {
          console.log("请求失败：" + "err");
        });
    },
    // 支付
    // 学米兑换微信支付
    async getWxPay(e) {
      if (parseInt(this.xuepay) < 10) {
        wx.showToast({
          title: "金额不小于10元",
          icon: "none",
        });
        return;
      }
      if (this.payThree) return;
      this.payThree = true;
      var that = this;
      this.radio = "1";
      // let LmAuthorId = await new Promise((resolve) => {
      //   wx.request({
      //     url: "https://lmapi.bosihw.cn/api/LmUserApi/DecryptForMiniApp",
      //     data: {
      //       Sign: "123",
      //       OpenId: wx.getStorageSync("AuthorId"),
      //     },
      //     method: "POST",
      //     success: (res) => {
      //       resolve(res);
      //     },
      //   });
      // });
      wx.login({
        provider: "weixin",
        success: (longRes) => {
          wx.request({
            url: "https://uniapp.bosihw.cn/api/AccountApi/Getcode2Session",
            data: {
              Code: longRes.code,
              journalId: 2020001,
            },
            method: "POST",
            success: (res) => {
              wx.setStorageSync("wxsession_key", res.data.data);
              wx.getUserInfo({
                provider: "weixin",
                success: async (res) => {
                  var wxId;
                  // localStorage.setItem('wxid',uni.getStorageSync('wxsession_key')
                  if (wx.getStorageSync("wxsession_key")) {
                    wxId = wx.getStorageSync("wxsession_key");
                  }
                  let getWxPay = await util.SaveWeChatUserInfo({
                    LmAuthorId: LmAuthorId.data,
                    wxId,
                    encryptedData: res.encryptedData,
                    iv: res.iv,
                  });

                  util
                    .getWxPay({
                      orderType: 3,
                      authorId: wx.getStorageSync("AuthorId"),
                      allNum: 1,
                      money: Number(this.xuepay),
                      cid: "string",
                    })
                    .then((res) => {
                      wx.requestPayment({
                        timeStamp: res.data.data.timeStamp,
                        nonceStr: res.data.data.nonceStr,
                        package: res.data.data.package,
                        paySign: res.data.data.paySign,
                        signType: "MD5",
                        success: (res) => {
                          wx.redirectTo({
                            url: "/pages/paysuccess/main?type=3",
                          });
                        },
                        complete: (err) => {
                          this.payThree = false;
                        },
                        fail: () => {
                          wx.showToast({
                            title: "支付失败",
                            icon: "error",
                            duration: 2000,
                          });
                          
                        },
                      });
                    });
                },
                fail: () => {
                  this.payThree = false;
                  wx.showToast({
                    title: "支付失败,请重新尝试",
                     icon: "error",
                  });
                },
              });
            },
            fail: () => {
              this.payThree = false;
              wx.showToast({
                title: "支付失败,请重新尝试",
                 icon: "error",
              });
            },
          });
        },
        fail: () => {
          this.payThree = false;
        },
      });
     
    },
    // 学米兑换支付宝支付
    getzfbPay() {
      this.moxezfbdata = util.zfbpaydetail(2, 3, this.xuepay, "string");
      this.moxezfbdata.then((res) => {
        if (res.data.data.Code == 200) {
          let divForm = document.getElementsByTagName("divform");
          if (divForm.length) {
            document.body.removeChild(divForm[0]);
          }
          const div = document.createElement("divform");

          div.innerHTML = res.data.data.data.responseBody;
          document.body.appendChild(div);
          document.forms[0].acceptCharset = "UTF-8";
          document.forms[0].setAttribute("target", "_blank");
          document.forms[0].submit();
        } else if (res.data.code) {
          let divForm = document.getElementsByTagName("divform");
          if (divForm.length) {
            document.body.removeChild(divForm[0]);
          }
          const div = document.createElement("divform");

          div.innerHTML = res.data.data.responseBody;
          document.body.appendChild(div);
          document.forms[0].acceptCharset = "UTF-8";
          document.forms[0].setAttribute("target", "_blank");
          document.forms[0].submit();
        }
      });
    },
    // 立即兑换，展开支付方式
    getdhpaymethods() {
      if (this.xuepay == "") {
        wx.showToast({ title: "金额不能为空", icon: "none" });
        // this.perdisabled = false
      } else if (Number(this.xuepay) < 10) {
        wx.showToast({ title: "金额不可小于10元!", icon: "none" });
        // this.perdisabled = false
      } else {
        this.patMethodsShow = true;
      }
    },
    // 获取个人信息
    getuserinfo() {
      this.$httphelper
        .post("/api/LmUserApi/GetAuthorInfo", {
          Sign: "string",
          OpenId: this.$localStorage.getItem("AuthorId"),
        })
        .then((res) => {
          this.xuemi = res.data.data.Money;
          localStorage.setItem("xuemi", this.xuemi);
        })
        .catch((err) => {
          console.log("请求失败：" + "err");
        });
    },
  },
  onLoad() {
    this.xuepay = "";
    this.patMethodsShow = false;
    this.getInfo();
    this.getuserinfo();
  },
  mounted() {
    let query = wx.createSelectorQuery();
    query
      .select(".content")
      .boundingClientRect((rect) => {
        let height = rect.height;
        wx.createSelectorQuery()
          .select(".learnmiCont_pay")
          .boundingClientRect((rect) => {
            height += rect.height;
            wx.createSelectorQuery()
              .select(".learnmiCont_pay_right")
              .boundingClientRect((rect) => {
                height += rect.height;
                console.log(height, "快快快");
                this.scrollHeight =
                  wx.getSystemInfoSync().windowHeight - height;
              })
              .exec();
          })
          .exec();
      })
      .exec();
    this.getInfo();
  },
};
</script>

<style lang="less" scoped>
@media screen and (min-width: 1010px) {
  #learnmi {
    display: none;
  }
}
@media screen and (max-width: 1010px) {
  /deep/.el-pagination {
    width: 100%;
    text-align: center;
    overflow: hidden;
    overflow-x: auto;
    margin-top: 10px;
  }
  .el-pagination::-webkit-scrollbar {
    display: none;
  }
  #url {
    box-sizing: border-box;
  }
  #learnmi {
    width: 100%;
    .learnmiCont {
      width: 100%;
      height: 100%;
      background: #f0f0f0;
      .learnmiCont_top {
        width: 100%;
        height: 162px;
        background: url("https://uniappfile.bosihw.cn/Res/BosihuiwenRes/yyqklm/Vip/xmbg.png")
          no-repeat;
        background-size: cover;
        position: relative;
        p:nth-child(1),
        p:nth-child(2) {
          font-size: 18px;
          color: #fff;
          text-align: center;
          position: relative;
          top: 40px;
        }
        p:nth-child(2) {
          top: 48px;
        }
        .learnmiCont_top_bot {
          width: 100%;
          height: 48px;
          background: rgba(0, 0, 0, 0.2);
          position: absolute;
          bottom: 0;
          padding: 4px 12px;
          color: #fff;
          font-size: 13px;
          text-align: justify;
          box-sizing: border-box;
        }
      }
      .learnmiCont_pay {
        width: 100%;
        height: 50px;
        background: #fff;
        .learnmiCont_pay_left {
          width: 36%;
          float: left;
          margin-top: 10px;
          margin-left: 13%;
          display: flex;
          align-items: center;
          input {
            width: 72%;
            border: none;
            outline: none;
            border-bottom: 1px solid #2859ff;
            font-size: 13px;
            color: #9d9d9d;
          }
          /deep/.el-input__inner {
            border: none;
            border-bottom: 1px solid #2859ff;
          }
        }
        .learnmiCont_pay_right {
          width: 27%;
          float: right;
          height: 31px;
          background: #2859ff;
          border-radius: 23px;
          color: #fff;
          font-size: 15px;
          text-align: center;
          // line-height: 1px;
          line-height: 31px;
          margin-right: 11%;
          margin-top: 3%;
        }
      }
      .learnmiCont_paymethods {
        width: 100%;
        height: auto;
        background: #fff;
        margin-top: 15px;
        padding: 10px 15px 0 15px;
        .acacirleCont_pay_cont {
          width: 100%;
          .acacirleCont_pay_line {
            display: inline-block;
            height: 15px;
            border-left: 1px solid #ff7301;
          }
          span {
            color: #000;
            font-weight: bold;
            font-size: 15px;
            margin-left: 10px;
          }
        }
        ul {
          width: 100%;
          margin-top: 12px;
          li {
            list-style: none;
            padding: 5px 20px 10px 5px;
            border-bottom: 1px solid #f0f0f0;
            img {
              display: inline-block;
              width: 30px;
              height: 30px;
            }
            .el-radio {
              width: 77%;
              color: #3d3d3d;
              font-size: 15px;
              margin-left: 15px;
              position: relative;
              top: -9px;
              /deep/.el-radio__input {
                position: absolute;
                right: 0;
              }
              /deep/.el-radio__label {
                color: #3d3d3d;
                font-size: 15px;
              }
            }
          }
        }
      }

      .learnmiCont_cont {
        width: 100%;
        background: #fff;
        height: auto;
        margin-top: 15px;
        ul {
          // padding: 10px;
          li:nth-child(1) {
            color: #000;
            font-size: 18px;
            border: none;
          }
          li {
            list-style: none;
            padding: 15px;
            border-bottom: 1px solid #eeeeee;
            p:nth-child(1) {
              width: 100%;
              height: 30px;
              span:nth-child(1) {
                font-size: 16px;
                color: #000;
                float: left;
              }
              span:nth-child(2) {
                font-size: 16px;
                color: #000;
                float: right;
              }
            }
            p:nth-child(2) {
              color: #9d9d9d;
              font-size: 14px;
              margin-top: 10px;
            }
          }
        }
      }
    }
  }
}
.consumption {
  text-align: center;
  margin-top: 100px;
}
</style>
